<?php

namespace app\common\business;

use app\common\model\mysql\Goods as GoodsModel;
use app\common\business\GoodsSku as GoodsSkuBus;
use think\Exception;

class Goods extends BaseBus
{
    public $Model = null;
    public function __construct()
    {
        $this->Model = new GoodsModel();
    }

    public function insertData($data)
    {
        // 开启事务
        $this->Model->startTrans();

        try {
            $goodId = $this->add($data);//        dump($goodId);
            if (!$goodId) {
                return $goodId;
            }
            if ($data['goods_specs_type'] == 1) {
                $goodSkuData = [
                    'goods_id' => $goodId,
                ];
            } elseif ($data['goods_specs_type'] == 2) {
                $data['goods_id'] = $goodId;
                $res = (new GoodsSkuBus())->saveAll($data);
                //            dump($res);
                //            exit();
                $stock = array_sum(array_column($res, "stock"));

                $goodsUpdateData = [
                    'price' => $res[0]['price'],
                    'cost_price' => $res[0]['cost_price'],
                    'stock' => $stock,
                    'sku_id' => $res[0]['id']
                ];
                //            dump($goodsUpdateData);
                //            exit();
                $goodsRes = $this->Model->updateById($goodId, $goodsUpdateData);
                if (!$goodsRes) {
                    throw new Exception("insertData:goods主表更新失败");
                }

            } else {
                throw new Exception("规格类型存在");
            }//事务提交
            $this->Model->commit();
            return true;
        } catch (Exception $e) {
//            throw new Exception("内部异常",$e->getMessage());
            $this->Model->rollback();
            return false;
        }

    }

}